package com;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class App {

	private ServerSocket server;
	private Socket socket;

	void startServer() {
		try {
			server = new ServerSocket(8848);
			System.out.println("服务器套接字创建成功等待连接");
			while (true) {
				socket = server.accept();
				new HandlerThread(socket);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private class HandlerThread implements Runnable {
		private Socket socket;
		private String key;

		private InputStreamReader reader = null;
		char chars[] = new char[64];
		int len;
		private String temp = null;

		public HandlerThread(Socket client) {
			socket = client;
			new Thread(this).start();
		}

		public void run() {
			key = socket.getInetAddress().toString().substring(1) + "|" + socket.getPort() + " ";
			System.out.println(key + "已连接");
			try {
				InputStreamReader isr=new InputStreamReader(socket.getInputStream());//接收客户端的数据
				BufferedReader br=new BufferedReader(isr);//存入缓存
				temp=br.readLine();
				while (temp.length()>0) {
					System.out.println(temp);
					temp=br.readLine();
				}
//				reader = new InputStreamReader(socket.getInputStream());
//				while ((len = reader.read(chars)) != -1) {
//					temp = new String(chars, 0, len);
//					for(int i=0;i<len;i++) {
//						System.out.print((int)chars[i]+",");
//					}
//					System.out.println();
//					System.out.println(key+len+" :"+temp);
//				}
				if (socket.getKeepAlive() == false) {
					reader.close();
					System.out.println("客户端" + key + "-->退出");
					socket.close();
				}
			} catch (Exception e) {

			}
			System.out.println(key + "断开连接");
		}
	}

	public static void main(String[] args) {
		App tcp = new App();
		tcp.startServer();
	}
}
